module WWW
  class Tkd
    class TbSellerOrder < ActiveRecord::Base
      #根据最后修改时间对Seller Order进行排序并搜索
      def self.find_on_page(user_id,page_num, page_size)

        find(:all,

        :conditions => "user_id = "+user_id.to_s,

        :order => "updated_at desc",

        :limit => page_size,

        :offset => page_num)

      end
      #判断订单是否存在
      def self.find_from_order_id_and_user_id(order_id,user_id)
        return self.find_by_order_id_and_user_id(order_id,user_id)
      end
      #根据tid与user_id获得订单信息
      def self.find_from_tid_and_user_id(tid,user_id)
        order = WWW::Tkd::TbOrder.find_by_tid tid#这里可能遇到t_order没有的记录哦
        if order!=nil
         return self.find_from_order_id_and_user_id(order.id,user_id)
        end
        return nil
      end
      #计算总数
      def self.count(user_id)
        return self.count_by_sql(["select count(id) from tb_seller_orders where user_id = ?", user_id])
      end
      #将Taobao的数据导入到tb_order表中，并与tb_seller_order进行关联
      def self.save_from_tabao items,session
        if items['trade']!=nil
          conv = Iconv.new("UTF-8","GB2312")
          items['trade'].each do|item|
            order = WWW::Tkd::TbOrder.find_by_tid item['tid'][0].strip().to_s
            if order==nil
              order = WWW::Tkd::TbOrder.new
              order.seller_nick = item['seller_nick'][0].strip() unless item['seller_nick']==nil
              order.buyer_nick = item['buyer_nick'][0].strip() unless item['buyer_nick']==nil
              order.iid = item['iid'][0].strip() unless item['iid']==nil
              order.title=item['title'][0].strip() unless item['title']==nil
              order.price=item['price'][0].strip() unless item['price']==nil
              order.pic_path=item['pic_path'][0].strip() unless item['pic_path']==nil
              order.num=item['num'][0].strip() unless item['num']==nil
              order.tid=item['tid'][0].strip() unless item['tid']==nil
              order.order_created_at=item['created'][0].strip() unless item['created']==nil
              order.status=item['status'][0].strip() unless item['status']==nil
              order.seller_rate=item['seller_rate'][0].strip() unless item['seller_rate']==nil
              order.buyer_rate=item['buyer_rate'][0].strip() unless item['buyer_rate']==nil
              order.save
            end
            #将order与user关联到seller_order表中
            seller_order = self.find_by_user_id_and_order_id(session[:id],order.id)
              if seller_order==nil
                seller_order=self.new
                seller_order.user_id=session[:id]
                seller_order.order_id=order.id
                seller_order.save
              end

          end
        end
      end
    end
  end
end
